package com.salt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.salt.common.Result;
import com.salt.entity.IdleAffiliateCpsIncomeDetail;
import com.salt.entity.User;
import com.salt.service.IdleAffiliateCpsIncomeDetailService;
import com.salt.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 闲鱼联盟CPS佣金明细控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/cps-income")
@RequiredArgsConstructor
public class IdleAffiliateCpsIncomeDetailController {

    private final IdleAffiliateCpsIncomeDetailService incomeDetailService;

    /**
     * 获取佣金明细汇总数据
     * @param startDate 开始日期，格式：yyyy-MM-dd
     * @param endDate 结束日期，格式：yyyy-MM-dd
     * @return 汇总数据
     */
    @GetMapping("/summary")
    public Map<String, Object> getIncomeSummary(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        
        log.info("接收到佣金明细汇总查询请求，开始日期：{}，结束日期：{}", startDate, endDate);

        User user = UserContext.getUser();
        Map<String, Object> result = new HashMap<>();
        try {
            // 转换日期字符串为LocalDate
            LocalDate start = LocalDate.parse(startDate);
            LocalDate end = LocalDate.parse(endDate);
            
            // 转换为Date类型，并设置时间范围
            Date startDateTime = java.util.Date.from(
                start.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant()
            );
            Date endDateTime = java.util.Date.from(
                end.atTime(LocalTime.MAX).atZone(java.time.ZoneId.systemDefault()).toInstant()
            );
            
            Map<String, Object> summary = incomeDetailService.getIncomeSummary(startDateTime, endDateTime,user.getInviteCode());
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", summary);
        } catch (Exception e) {
            log.error("查询佣金明细汇总数据失败", e);
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 分页查询佣金明细数据
     * @param current 当前页码，从1开始
     * @param size 每页大小
     * @param startDate 开始日期，格式：yyyy-MM-dd
     * @param endDate 结束日期，格式：yyyy-MM-dd
     * @param billState 账单状态：1-待发放，2-已发放，3-已取消
     * @param orderState 订单状态：1-创建订单，2-交易完成，3-交易取消，4-交易付款
     * @param hasCoupon 是否有优惠券
     * @param keyword 关键词（商品标题或订单ID）
     * @return 分页数据
     */
    @GetMapping("/page")
    public Result<IPage<IdleAffiliateCpsIncomeDetail>> pageQuery(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) Integer billState,
            @RequestParam(required = false) Integer orderState,
            @RequestParam(required = false) Boolean hasCoupon,
            @RequestParam(required = false) String keyword) {
        try {
            // 获取当前用户
            User user = UserContext.getUser();
            if (user == null) {
                return Result.error("用户未登录");
            }
            // 转换日期字符串为Date类型
            Date startDateTime = null;
            Date endDateTime = null;

            if (startDate != null && !startDate.isEmpty()) {
                LocalDate start = LocalDate.parse(startDate);
                startDateTime = java.util.Date.from(
                        start.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant()
                );
            }

            if (endDate != null && !endDate.isEmpty()) {
                LocalDate end = LocalDate.parse(endDate);
                endDateTime = java.util.Date.from(
                        end.atTime(LocalTime.MAX).atZone(java.time.ZoneId.systemDefault()).toInstant()
                );
            }

            // 创建分页对象
            Page<IdleAffiliateCpsIncomeDetail> page = new Page<>(current, size);

            // 执行分页查询
            IPage<IdleAffiliateCpsIncomeDetail> pageResult = incomeDetailService.pageQuery(
                    page,
                    startDateTime,
                    endDateTime,
                    billState,
                    orderState,
                    hasCoupon,
                    keyword,
                    user.getInviteCode()
            );

            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询CPS佣金明细失败", e);
            return Result.error(e.getMessage());
        }
    }
} 